package com.example.portdemo.view;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;

import com.example.portdemo.Adapter.NewsAdapter;
import com.example.portdemo.R;
import com.example.portdemo.date.model.NewsEntity;
import com.example.portdemo.viewModel.NewsViewModel;

import java.util.List;

import io.reactivex.rxjava3.annotations.Nullable;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class NewsFragment extends Fragment {
    private NewsViewModel newsViewModel;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        newsViewModel = new ViewModelProvider(this).get(NewsViewModel.class);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_news, container, false);

        // Observe the news list
        newsViewModel.getNewsList(new Callback<List<NewsEntity>>() {
            @Override
            public void onResponse(Call<List<NewsEntity>> call, Response<List<NewsEntity>> response) {
            }

            @Override
            public void onFailure(Call<List<NewsEntity>> call, Throwable throwable) {
            }
        }).observe(getViewLifecycleOwner(), newsEntities -> {
            // Update the UI with the received news list
            NewsAdapter adapter = new NewsAdapter(newsEntities);
            RecyclerView recyclerView = view.findViewById(R.id.recyclerView);
            recyclerView.setAdapter(adapter);
        });

        // Load the news list
        newsViewModel.loadNewsList();

        return view;
    }
}
